package user

import (
	"fmt"
	"gpt-api/framework/cache"
	"gpt-api/framework/cos"
	"gpt-api/framework/db"
	"gpt-api/framework/ginplus"
	"gpt-api/pkg/model"
	"gpt-api/pkg/pay"

	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

type Handler struct {
	db     *db.DB
	cache  *cache.RedisClient
	payers map[pay.Channel]pay.Payer
}

func New(db *db.DB) *Handler {
	payers := make(map[pay.Channel]pay.Payer)
	//payers[pay.WeChatPay1] = pay.NewWechat1()
	//payers[pay.SandeChannel] = pay.NewSandePay()
	//payers[pay.WechatChannel] = pay.NewWechat()
	return &Handler{db: db, payers: payers}
}

// 获取用户信息
func (h *Handler) GetUser(c *gin.Context) error {
	userId := ginplus.GetUserID(c)
	// 打印用户id
	fmt.Println("Get user", userId)
	// 获取auther的用户信息
	userInfo, err := (&model.Users{}).GetUserInfoById(h.db, userId)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, userInfo)
}

// 更新用户信息
func (h *Handler) UpdateUser(c *gin.Context) error {
	userId := ginplus.GetUserID(c)

	// 获取auther的用户信息
	userInfo, err := (&model.Users{}).GetUserInfoById(h.db, userId)
	if err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	var req struct {
		Username string `json:"username"`
		Gender   int    `json:"gender"`
		Avatar   string `json:"avatar"`
		Phone    string `json:"phone"`
	}

	if err := c.Bind(&req); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}

	// 输出req的内容
	// log.Info("Update user", log.Var("req", req))
	fmt.Println("Update user", req.Username)

	if req.Username != "" {
		userInfo.Username = req.Username
	}

	if req.Avatar != "" {
		userInfo.Avatar = req.Avatar
	}

	if req.Phone != "" {
		userInfo.Phone = req.Phone
	}

	if req.Gender != userInfo.Gender {
		userInfo.Gender = req.Gender
	}

	if err := userInfo.Update(h.db); err != nil {
		return ginplus.ReplyInternalError(c, err)
	}

	return ginplus.ReplyJSON(c, userInfo)
}

// 头像上传
func (h *Handler) UploadImage(c *gin.Context) error {
	// 限制上传文件大小为 1M
	if err := c.Request.ParseMultipartForm(5 << 20); err != nil {
		return ginplus.ReplyBadRequest(c, err)
	}
	// 上传文件
	savePath := viper.GetString("FileUploadSetting.CosPictureSavePath")
	if r, finnalSavePath := cos.Upload(c, savePath); r == true {
		return ginplus.ReplyJSON(
			c,
			finnalSavePath,
		)
	}
	return ginplus.ReplyInternalError(c, fmt.Errorf("upload file failed"))
}
